package com.igelato.controller.PayGoods;

import com.alibaba.fastjson2.JSONObject;
import com.igelato.model.PayReq;
import com.igelato.response.R;
import com.igelato.service.OrderGoodsService;
import com.igelato.service.PayGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * ClassName: PayController
 * Package: com.tencent.wxcloudrun.controller
 * Description:
 *
 * @Date: 2023/1/22 8:34 AM
 * @Author: wht
 */
@Slf4j
@RestController
@RequestMapping("/2c")
public class PayGoodsController {
    @Autowired
    OrderGoodsService orderGoodsService;
    @Autowired
    PayGoodsService payGoodsService;

    @PostMapping("/payByBalance")
    public <T> R<T> payByBalance(@RequestBody PayReq payReq) {
        payGoodsService.payByBalance(payReq);

        return R.successMsg("支付成功！");
    }

    @PostMapping("/payByWx")
    public <T> R<T> payByWx(@RequestHeader("X-WX-OPENID") String openid, @RequestBody PayReq payReq) {
        JSONObject payment = payGoodsService.payByWx(openid, payReq);

        return R.successData(payment);
    }

    @PostMapping("/paygoods_callback")
    public JSONObject payGoodsCallback(@RequestBody Map mapBody) {
//判断是否支付成功
        if (!mapBody.get("returnCode").equals("SUCCESS")) {
            JSONObject json = new JSONObject();
            json.put("errcode", 999);
            json.put("errmsg", "ERROR");
            return json;
        }

//        更新订单状态
        payGoodsService.wxPayCallback(mapBody);

//返回
        JSONObject json = new JSONObject();
        json.put("errcode", 0);
        json.put("errmsg", "");
        return json;
    }

    @GetMapping("/queryOrder/{out_trade_no}")
    public <T> R<T> queryOrder(@PathVariable String out_trade_no) {
        String trade_state = payGoodsService.queryOrder(out_trade_no);
        return R.successData(trade_state);
    }


}
